/**
 * @author: 孙志阳
 * @date:   2022-8-5
 * @description: 封装请求
 */
import axios from 'axios';
import { defAxios, defService, uploadAxios } from '@/utils/http/index';
import { baseURL } from '@/config/modules/network';

/**
 * @name: 封装axios get方法
 * @param url 请求连接
 * @param params 请求参数
 * @param callback 回调方法
 */
export function Iget(url, params, callback) {
	return new Promise((resolve, reject) => {
		defAxios
			.get(url, { params: unref(params) })
			.then((res) => {
				callback ? resolve(callback(res)) : resolve(res);
			})
			.catch((err) => {
				reject({ code: 500, msg: err });
			});
	});
}

/**
 * @name: axios post方法
 * @param url 请求连接
 * @param params 请求参数
 * @param callback 回调方法
 */
export function Ipost(url, data, callback) {
	return new Promise((resolve, reject) => {
		defAxios
			.post(url, unref(data))
			.then((res) => {
				callback ? resolve(callback(res)) : resolve(res);
			})
			.catch((err) => {
				reject({ code: 500, msg: err });
			});
	});
}

export function Iput(url, data, callback) {
	return new Promise((resolve, reject) => {
		defAxios
			.put(url, unref(data))
			.then((res) => {
				callback ? resolve(callback(res)) : resolve(res);
			})
			.catch((err) => {
				reject({ code: 500, msg: err });
			});
	});
}

export function Idelete(url, params, callback) {
	return new Promise((resolve, reject) => {
		defAxios
			.delete(url, { params: unref(params) })
			.then((res) => {
				callback ? resolve(callback(res)) : resolve(res);
			})
			.catch((err) => {
				reject({ code: 500, msg: err });
			});
	});
}

export function Iupload(url, data, progress, cancel) {
	const CancelToken = axios.CancelToken;
	return uploadAxios.request({
		url: url,
		method: 'POST',
		headers: {
			'Content-Type': 'multipart/form-data',
		},
		data: data,
		onUploadProgress: function (progressEvent) {
			progress && progress(parseInt((progressEvent.loaded / progressEvent.total) * 100));
		},
		cancelToken: new CancelToken(function executor(c) {
			cancel && cancel(c);
		}),
	});
}

export function Idownload(url, params, callback) {
	return new Promise((resolve, reject) => {
		defService()
			.request({ url: baseURL + url, params: unref(params), responseType: 'blob' })
			.then((res) => {
				callback ? resolve(callback(res)) : resolve(res);
			})
			.catch((err) => {
				reject({ code: 500, msg: err });
			});
	});
}
